package com.minimalist.lindi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpStatus;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.config.mybatis.bo.PageResp;
import com.minimalist.common.entity.basic.vo.file.FileVO;
import com.minimalist.common.entity.lindi.po.LindiTradeApplicationContract;
import com.minimalist.common.entity.lindi.vo.contracttemplate.LindiContractTemplateVO;
import com.minimalist.common.entity.lindi.vo.tradeapplicationcontract.LindiTradeApplicationContractQueryVO;
import com.minimalist.common.entity.lindi.vo.tradeapplicationcontract.LindiTradeApplicationContractVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.response.R;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.manager.ContractTemplateManager;
import com.minimalist.lindi.mapper.LindiTradeApplicationContractMapper;
import com.minimalist.lindi.service.LindiTradeApplicationContractService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 林地指标交易平台_交易申请合同表 服务层实现。
 *
 * @author 11987
 * @since 2025-06-03
 */
@Service
public class LindiTradeApplicationContractServiceImpl extends ServiceImpl<LindiTradeApplicationContractMapper, LindiTradeApplicationContract> implements LindiTradeApplicationContractService{

    private static final Logger logger = LoggerFactory.getLogger(LindiTradeApplicationContractServiceImpl.class);

    @Autowired
    private LindiTradeApplicationContractMapper mapper;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Autowired
    private ContractTemplateManager contractTemplateManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTradeApplicationContract(
            LindiTradeApplicationContractVO tradeApplicationContractVO){
        LindiTradeApplicationContract contract = new LindiTradeApplicationContract();
        BeanUtil.copyProperties(tradeApplicationContractVO, contract);
        contract.setTradeApplicationContractId(UnqIdUtil.uniqueId());
        contract.setCreateId(tradeApplicationContractVO.getCreateId());
        contract.setUpdateId(tradeApplicationContractVO.getUpdateId());
        contract.setCreateTime(tradeApplicationContractVO.getCreateTime());
        contract.setUpdateTime(tradeApplicationContractVO.getUpdateTime());

        int insert = mapper.insert(contract, true);
        Assert.isTrue(insert == 1, () -> new BusinessException("添加交易申请合同失败"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTradeApplicationContractByTradeApplicationContractId(Long tradeApplicationContractId){
        LindiTradeApplicationContract contract = mapper.selectTradeApplicationContractByTradeApplicationContractId(tradeApplicationContractId);
        Assert.notNull(contract, () -> new BusinessException("交易申请合同不存在"));

        // 删除关联的文件
        if (contract.getContractFileId() != null){
            try{
                R<Void> result = fileFeignClient.deleteFile(contract.getContractFileId());
                if (result.getCode() != 200){
                    logger.warn("删除合同文件失败，文件ID: {}, 错误信息: {}", contract.getContractFileId(), result.getMessage());
                }
            } catch (Exception e){
                logger.warn("删除合同文件异常，文件ID: {}, 异常信息: {}", contract.getContractFileId(), e.getMessage());
            }
        }

        int delete = mapper.delete(contract);
        Assert.isTrue(delete == 1, () -> new BusinessException("删除交易申请合同失败"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTradeApplicationContractByTradeApplicationContractId(
            LindiTradeApplicationContractVO tradeApplicationContractVO){
        LindiTradeApplicationContract contract = mapper
                .selectTradeApplicationContractByTradeApplicationContractId(
                        tradeApplicationContractVO.getTradeApplicationContractId());
        Assert.notNull(contract, () -> new BusinessException("交易申请合同不存在"));

        BeanUtil.copyProperties(tradeApplicationContractVO, contract, CopyOptions.create().ignoreNullValue());
        contract.setUpdateTime(LocalDateTime.now());

        int update = mapper.update(contract);
        Assert.isTrue(update == 1, () -> new BusinessException("更新交易申请合同失败"));
    }

    @Override
    public PageResp<LindiTradeApplicationContractVO> getPageTradeApplicationContractList(LindiTradeApplicationContractQueryVO queryVO){
        // 分页查询
        Page<LindiTradeApplicationContract> contractPage = mapper.selectPageTradeApplicationContractList(queryVO);

        // 数据转换
        List<LindiTradeApplicationContractVO> voList = BeanUtil.copyToList(contractPage.getRecords(), LindiTradeApplicationContractVO.class);

        // 填充文件信息
        for (LindiTradeApplicationContractVO vo : voList){
            if (vo.getContractFileId() != null){
                R<FileVO> fileResult = fileFeignClient.getFileByFileId(vo.getContractFileId());
                if (fileResult.getCode() == 200 && fileResult.getData() != null){
                    vo.setContractFile(fileResult.getData());
                }
            }
        }

        return new PageResp<>(voList, contractPage.getTotalRow());
    }

    @Override
    public LindiTradeApplicationContractVO getTradeApplicationContractByTradeApplicationContractId(Long tradeApplicationContractId){
        LindiTradeApplicationContract contract = mapper.selectTradeApplicationContractByTradeApplicationContractId(tradeApplicationContractId);
        Assert.notNull(contract, () -> new BusinessException("交易申请合同不存在"));

        LindiTradeApplicationContractVO vo = BeanUtil.copyProperties(contract, LindiTradeApplicationContractVO.class);

        // 填充文件信息
        if (contract.getContractFileId() != null){
            R<FileVO> fileResult = fileFeignClient.getFileByFileId(contract.getContractFileId());
            if (fileResult.getCode() == HttpStatus.HTTP_OK && fileResult.getData() != null){
                vo.setContractFile(fileResult.getData());
            }
        }

        return vo;
    }

    @Override
    public List<LindiTradeApplicationContract> getTradeApplicationContractListByTradeApplicationContractId(Long tradeApplicationContractId){
        List<LindiTradeApplicationContract> contractList = mapper.selectTradeApplicationContractListByTradeApplicationContractId(tradeApplicationContractId);
        Assert.notEmpty(contractList, () -> new BusinessException("交易申请合同列表不存在"));
        return contractList;
    }

    @Override
    public List<LindiTradeApplicationContractVO> getTradeApplicationContractListByTradeApplicationId(Long tradeApplicationId){
        List<LindiTradeApplicationContract> contractList = mapper
                .selectTradeApplicationContractListByTradeApplicationId(tradeApplicationId);

        // 数据转换
        List<LindiTradeApplicationContractVO> voList = BeanUtil.copyToList(contractList, LindiTradeApplicationContractVO.class);

        // 填充文件信息
        for (LindiTradeApplicationContractVO vo : voList){
            if (vo.getContractFileId() != null){
                R<FileVO> fileResult = fileFeignClient.getFileByFileId(vo.getContractFileId());
                if (fileResult.getCode() == HttpStatus.HTTP_OK && fileResult.getData() != null){
                    vo.setContractFile(fileResult.getData());
                }
            }
        }

        return voList;
    }

    @Override
    public List<LindiContractTemplateVO> getContractTemplateList(){
        return contractTemplateManager.getContractTemplateList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LindiTradeApplicationContractVO generateContract(Long tradeApplicationId
            , Long contractTemplateId, Long createId, Long tenantId){
        return null;
//        // TODO: 实现合同生成逻辑
//        // 1. 根据合同模板ID获取模板信息
//        // 2. 根据交易申请ID获取交易申请信息
//        // 3. 使用模板和交易申请信息生成合同文件
//        // 4. 保存合同记录
//
//        Long fileId = contractTemplateManager.generateContract(
//                tradeApplicationId, contractTemplateId, createId, tenantId);
//        LindiTradeApplicationContract contract = new LindiTradeApplicationContract();
//        contract.setTradeApplicationContractId(UnqIdUtil.uniqueId());
//        contract.setTradeApplicationId(tradeApplicationId);
//        contract.setContractTemplateId(contractTemplateId);
//        contract.setContractTemplateFileId(fileId);
//        contract.setCreateId(createId);
//        contract.setUpdateId(createId);
//        LocalDateTime now = LocalDateTime.now();
//        contract.setCreateTime(now);
//        contract.setUpdateTime(now);
//
//        int insert = mapper.insert(contract, true);
//        Assert.isTrue(insert == 1, () -> new BusinessException("生成合同失败"));
//
//        LindiTradeApplicationContractVO lindiTradeApplicationContractVO
//                = BeanUtil.copyProperties(contract, LindiTradeApplicationContractVO.class);
//
//        R<FileVO> fileByFileId = fileFeignClient.getFileByFileId(fileId);
//        Assert.isTrue(fileByFileId.getCode() == HttpStatus.HTTP_OK
//                        && fileByFileId.getData() != null
//                , () -> new BusinessException("获取合同文件失败"));
//        lindiTradeApplicationContractVO.setContractTemplateFile(fileByFileId.getData());
//        return lindiTradeApplicationContractVO;
    }

    /**
     * 生成合同编号
     *
     * @return 合同编号
     */
    private String generateContractNumber(){
        return "HT" + System.currentTimeMillis();
    }
}
